package server

import (
	"common/database/config"
	"context"
	"errors"
	"golang.org/x/crypto/bcrypt"
	"project_user_srv/internal/models/dao"
	"project_user_srv/internal/models/service"
	pb "project_user_srv/proto"
)

type Server struct {
	pb.UnimplementedUserServer
}

func (c *Server) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	password, _ := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
	user := dao.User{
		Username: request.Username,
		Password: string(password),
	}
	err := config.DB.Create(&user).Error
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &pb.RegisterResponse{Id: int64(user.ID)}, nil
}

func (c *Server) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	var user *dao.User
	err := config.DB.Where("username=?", request.Username).Limit(1).Find(&user).Error
	if err != nil {
		return nil, errors.New("没有这个用户")
	}
	if user.ID == 0 {
		return nil, errors.New("没有这个用户")
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
	if err != nil {
		return nil, errors.New("密码错误")
	}
	return &pb.LoginResponse{Id: int64(user.ID)}, nil
}

func (c *Server) Home(ctx context.Context, request *pb.HomeRequest) (*pb.HomeResponse, error) {
	list := service.List(request)
	var sli []*pb.Videos
	for _, v := range list {
		one := pb.Videos{
			UserId:     int64(v.UserId),
			Video:      v.Video,
			VideoTitle: v.VideoTitle,
			Address:    v.Address,
		}
		sli = append(sli, &one)
	}
	return &pb.HomeResponse{Video: sli}, nil
}
